package com.atguigu.exception;

import com.alibaba.fastjson.JSON;
import com.atguigu.result.Result;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * @Author: 翟文海
 * @Date: 2022/11/7/007 21:18
 * @Version: 1.0
 * @Description:
 **/
@ControllerAdvice
public class GlobalException {
    private static final String PAGE_BINDERROR = "common/bindError";
    private static final String PAGE_RUNTIME_ERROR = "common/runtimeError";

    @ExceptionHandler(BindException.class)
    public String handlerBindException(BindException bindException, Model model,
                                       HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<FieldError> fieldErrors = bindException.getFieldErrors();
        if (request.getHeader("accept").contains("application/json")) {
            Result<List<FieldError>> fail = Result.fail(fieldErrors);
            response.getWriter().write(JSON.toJSONString(fail));
            return null;
        } else {
            model.addAttribute("fieldErrors", fieldErrors);
            return PAGE_BINDERROR;
        }
    }

    @ExceptionHandler(RuntimeException.class)
    public String globalException(RuntimeException e,
                                  HttpServletResponse response,
                                  HttpServletRequest request) throws IOException {
        if (request.getHeader("accept").contains("application/json")) {
            Result<String> fail = Result.fail(e.getMessage());
            response.getWriter().write(JSON.toJSONString(fail));
            return null;
        }else{
            return PAGE_RUNTIME_ERROR;
        }
    }
}
